package com.yimi.yinhepda.views.load_module;

import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.pda.ym.base.BaseTitleActivity;
import com.pda.ym.callbacks.UICallBack;
import com.pda.ym.entity.bean.CarPlanTaskEntity;
import com.pda.ym.entity.bean.LoadBillTaskEntity;
import com.pda.ym.net.NetRequest;
import com.pda.ym.utils.Constants;
import com.pda.ym.utils.FastClick;
import com.uce.pda.activity.FitActivity;
import com.yimi.yinhepda.R;
import com.yimi.yinhepda.entity.bean.BaseDictEntity;
import com.yimi.yinhepda.entity.response.QueryBaseDictResponse;
import com.yimi.yinhepda.utils.Common;

import org.jetbrains.annotations.NotNull;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 000432
 */
public class LoadSuccessActivity extends BaseTitleActivity {
    public TextView carCode1, carCode2, sourceDept, car, weight1, weight2;
    private EditText carCode, src, desc, carNo, realWeight, checkWeight;
    private Button activity_load_success_btn;
    private LinearLayout moreLinearLayout;
    /**
     * 0-在线装车完成； 1-离线装车完成
     */
    private int type = 0;
    private String mCarNos = "";
    private String mNextStationCodes = "";
    private String mBizTypeCodes = "";
    private String mStowageNos = "";
    private String mNextStation = "";
    private String mTaskNo;

    @Override
    public int setContentViewId() {
        return R.layout.activity_load_success;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        initData();
    }

    private void initData() {
        mTaskNo = getIntent().getStringExtra("task");
        type = getIntent().getIntExtra("type", 0);
        if (type == 0) {
            if (LoadScanActivity.carPlanTaskEntityList == null) {
                return;
            }
            for (CarPlanTaskEntity task : LoadScanActivity.carPlanTaskEntityList) {
                if(task.getLoadTasks() != null){
                    for (LoadBillTaskEntity entity : task.getLoadTasks()) {
                        mStowageNos += entity.getStowageNo() + "/";
                        if (entity.getDestDeptName() != null) {
                            mNextStation += entity.getDestDeptName() + "/";
                        }
                        mNextStationCodes += entity.getDestDeptCode() + "/";
                        mBizTypeCodes += entity.getBizTypeCode() + "/";
                        if (entity.getCarNo() != null) {
                            if (!entity.getCarNo().equals("")) {
                                mCarNos += entity.getCarNo() + "/";
                            }
                        }
                    }
                }
            }
            if (mStowageNos.length() > 1) {
                mStowageNos = mStowageNos.substring(0, mStowageNos.length() - 1);
            }
            if (mNextStation.length() > 1) {
                mNextStation = mNextStation.substring(0, mNextStation.length() - 1);
            }
            if (mNextStationCodes.length() > 1) {
                mNextStationCodes = mNextStationCodes.substring(0, mNextStationCodes.length() - 1);
            }
            if (mCarNos.length() > 1) {
                mCarNos = mCarNos.substring(0, mCarNos.length() - 1);
            }
            if (mBizTypeCodes.length() > 1) {
                mBizTypeCodes = mBizTypeCodes.substring(0, mBizTypeCodes.length() - 1);
            }

            carCode.setText(mStowageNos);
            desc.setText(mNextStation);
            carNo.setText(mCarNos);
            src.setText(getIntent().getStringExtra("src"));
            realWeight.setText(getIntent().getStringExtra("realWeight") + "kg");
            checkWeight.setText(getIntent().getStringExtra("checkWeight") + "kg");
        } else {
            carCode1.setText("系统配载");
            carCode.setText(getIntent().getStringExtra("stowageNo"));
            carCode2.setText("本地配载");
            src.setText(getIntent().getStringExtra("carcode"));
            sourceDept.setText("始发部门");
            desc.setText(getIntent().getStringExtra("src"));
            car.setText("目的部门");
            carNo.setText(getIntent().getStringExtra("desc"));
            weight1.setText("装车票数");
            realWeight.setText(getIntent().getStringExtra("carNo"));
            weight2.setText("装车件数");
            checkWeight.setText(getIntent().getStringExtra("realWeight"));
        }

        findViewById(R.id.activity_load_success_btn).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    public String getPageName() {
        return "装车成功";
    }

    private void initView() {

        carCode = findViewById(R.id.activity_load_success_carcode);
        src = findViewById(R.id.activity_load_success_src);
        desc = findViewById(R.id.activity_load_success_desc);
        carNo = findViewById(R.id.activity_load_success_carno);
        realWeight = findViewById(R.id.activity_load_success_realweight);
        checkWeight = findViewById(R.id.activity_load_success_checkweight);

        carCode1 = findViewById(R.id.carCode1);
        carCode2 = findViewById(R.id.carCode2);
        sourceDept = findViewById(R.id.sourceDept);
        car = findViewById(R.id.car);
        weight1 = findViewById(R.id.weight1);
        weight2 = findViewById(R.id.weight2);
        moreLinearLayout = findViewById(R.id.more_layout);
        activity_load_success_btn = findViewById(R.id.activity_load_success_btn);
        activity_load_success_btn.setOnClickListener(this);
        findViewById(R.id.btn_sealCar).setOnClickListener(this);
        //设置加载任务标志
        setLoadTaskTag();
    }

    @Override
    public void onClick(View v) {
        if (FastClick.isFastClick()) {
            return;
        }
        switch (v.getId()) {
            case R.id.activity_load_success_btn:
                //设置加载任务标志
                setLoadTaskTag();
                finish();
                break;
            case R.id.btn_sealCar:
                if (!LoadScanActivity.carPlanTaskEntityList.isEmpty()) {
                    boolean hasBeTask = false;
                    for (CarPlanTaskEntity planTask : LoadScanActivity.carPlanTaskEntityList) {
                        if(planTask.getBeTask() == 1){
                            hasBeTask = true;
                        }
                    }
                    if (hasBeTask) {
                        //车线任务，获取数据字典配置：仓位上报开关（position_report_switch）
                        queryPositionReportSwitch();
                    } else {
                        toScanSealSignActivity();
                    }
                } else {
                    showToast("计划装车任务集合为空！");
                }
                break;
            default:
                break;
        }
    }

    /**
     * 数据字典：仓位上报开关（position_report_switch）
     * 值：当前登录部门
     * 参数1:干线开关,0-关闭,1-开启;
     * 参数2:支线开关,0-关闭,1-开启
     */
    private void queryPositionReportSwitch() {
        showPgDlg("查询配置中...");
        Map<String, String> params = new HashMap<>(2);
        params.put("dictCode", "position_report_switch");
        //查询类型，1-只查询未作废的，为null则查询所有(包含作废和未作废的)
        params.put("type", "1");

        new NetRequest().setMethod(NetRequest.Method.GET)
                .setResponsClazz(QueryBaseDictResponse.class)
                .setUrl(Constants.URL_QUERY_DICT)
                .setParams(params)
                .setConnTimeOut(10 * 1000)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        dismissPgDlg();
                        showToast(msg);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        dismissPgDlg();
                        QueryBaseDictResponse response = (QueryBaseDictResponse) obj;
                        List<BaseDictEntity> dictlist = response.getData();
                        if (dictlist != null && !dictlist.isEmpty()) {
                            for (BaseDictEntity item : dictlist) {
                                if (item.getDictValue().equals(sharedPreferUtil.getDeptCode())) {
                                    if (LoadScanActivity.carPlanTaskEntityList != null) {
                                        //获取装车配载单/发件任务，查询装车任务的干支线类型
                                        for (CarPlanTaskEntity task : LoadScanActivity.carPlanTaskEntityList) {
                                            if(task.getLoadTasks() != null){
                                                for (LoadBillTaskEntity loadEntity : task.getLoadTasks()) {
                                                    //运输方式：1-trunk_line干线,2-branch_line支线,3-car_load:整车
                                                    int bizType = loadEntity.getBizTypeCode();
                                                    if (bizType == 1 && "1".equals(item.getExternalParam1())) {
                                                        //干线开启，跳转至仓位上报界面
                                                        toFitActivity();
                                                        return;
                                                    } else if (bizType == 2 && "1".equals(item.getExternalParam2())) {
                                                        //支线开启，跳转至仓位上报界面
                                                        toFitActivity();
                                                        return;
                                                    }
                                                }
                                            }
                                        }
                                    } else {
                                        showToast("发车任务为空！");
                                    }
                                }
                            }
                        } else {
                            showToast("获取仓位上报配置失败！");
                        }
                        toScanSealSignActivity();
                    }
                });
    }

    /**
     * 跳转至封签扫描界面
     */
    private void toScanSealSignActivity() {
        Intent intent = new Intent(this, ScanSealSignActivity.class);
        intent.putExtra("stowageNos", mStowageNos);
        intent.putExtra("bizTypeCodes", mBizTypeCodes);
        intent.putExtra("carNos", mCarNos);
        intent.putExtra("nextStationCodes", mNextStationCodes);
        intent.putExtra("nextStation", mNextStation);
        intent.putExtra("carPlanTaskList", (Serializable) LoadScanActivity.carPlanTaskEntityList);
        intent.putExtra("taskNo", mTaskNo);
        startActivity(intent);
    }

    /**
     * 跳转至仓位上报界面
     */
    private void toFitActivity() {
        Intent intent = new Intent(LoadSuccessActivity.this, FitActivity.class);
        intent.putExtra("loadType", 1);
        intent.putExtra("stowageNos", mStowageNos);
        intent.putExtra("bizTypeCodes", mBizTypeCodes);
        intent.putExtra("carNos", mCarNos);
        intent.putExtra("nextStationCodes", mNextStationCodes);
        intent.putExtra("nextStation", mNextStation);
        intent.putExtra("carPlanTaskList", (Serializable) LoadScanActivity.carPlanTaskEntityList);
        intent.putExtra("taskNo", mTaskNo);
        startActivity(intent);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            setLoadTaskTag();
        }
        return false;
    }

    /**
     * 设置任务加载标志
     */
    private void setLoadTaskTag() {
        sharedPreferUtil.setBooleanValue(Common.SUCCESS_SUBMIT_LOAD, true);
    }

    @Override
    public boolean showBack() {
        return false;
    }

    @Override
    public void setBack() {

    }

    @NotNull
    @Override
    public String setTitle() {
        return getPageName();
    }

}
